package cc.sjfx.sharedoc.bmob;

import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import cc.sjfx.sharedoc.cache.UserCache;
import cc.sjfx.sharedoc.db.UserDB;
import cc.sjfx.sharedoc.utils.CheckUtils;
import cn.bmob.v3.BmobRealTimeData;
import cn.bmob.v3.listener.ValueEventListener;
import cn.mandroid.frame.toast.MLog;

public class BmobUpdate {
	static BmobRealTimeData data;

	public static void initListener(final Context context) {
		if (data == null) {
			data = new BmobRealTimeData();
		}
		data.start(context, new ValueEventListener() {
			@Override
			public void onDataChange(JSONObject arg0) {
				// TODO Auto-generated method stub
				MLog.i(arg0.toString());
				try {
					checkTable(context, arg0);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onConnectCompleted() {
				// TODO Auto-generated method stub
				if (data.isConnected()) {
					if (UserCache.user != null) {
						data.subRowUpdate("_User", UserCache.user.getObjectId());
					}
					List<UserDB> list = UserDB.getUserDB();
					if (list != null) {
						for (UserDB db : list) {
							data.subRowUpdate("_User", db.username);
						}
					}
					data.subTableUpdate("School");
				}
			}
		});
	}

	private static void checkTable(Context context, JSONObject arg0)
			throws JSONException {
		String table = arg0.getString("tableName");
		switch (CheckUtils.tableName(table)) {
		case 0:
			arg0 = new JSONObject(arg0.getString("data"));
			if (arg0.getString("username").equals(UserCache.user.getUsername())) {
				BmobCache.updateUser(context);
			}
			UserDB.updateData(context, arg0);
			break;

		default:
			break;
		}
	}
}
